package com.example.wechathook.hook;

import static de.robv.android.xposed.XposedBridge.log;
import static de.robv.android.xposed.XposedHelpers.callMethod;
import static de.robv.android.xposed.XposedHelpers.callStaticMethod;
import static de.robv.android.xposed.XposedHelpers.findAndHookMethod;
import static de.robv.android.xposed.XposedHelpers.findClass;
import static de.robv.android.xposed.XposedHelpers.getObjectField;
import static de.robv.android.xposed.XposedHelpers.newInstance;

import java.io.IOException;
import java.io.StringReader;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import android.database.Cursor;
import android.net.Uri;

import com.example.wechathook.util.PreferenceUtils;

import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.XposedHelpers;
import de.robv.android.xposed.callbacks.XC_LoadPackage;

/**
 * 自动抢红包
 * 
 * @author chencq
 *
 */
public class RedPacketHook extends BaseHook {

	@Override
	public void hook(final XC_LoadPackage.LoadPackageParam lpp) {
		try {
			findAndHookMethod("com.tencent.mm.d.b.bj", lpp.classLoader, "b", Cursor.class, new XC_MethodHook() {
				@Override
				protected void afterHookedMethod(MethodHookParam mhp) throws Throwable {
					if (!PreferenceUtils.locationSwtich()) {// 抢红包开关
						return;
					}

					int field_type = XposedHelpers.getIntField(mhp.thisObject, "field_type");
					log("xposed, field_type：" + field_type);
					if ((field_type == 436207665) || (field_type == 469762097)) {

						int status = (Integer) XposedHelpers.getObjectField(mhp.thisObject, "field_status");
						XposedBridge.log("xposed, status：" + status);
						if (status == 4) {
							return;
						}

						int isSend = (Integer) XposedHelpers.getObjectField(mhp.thisObject, "field_isSend");
						log("xposed, isSend：" + isSend);
						if (PreferenceUtils.notSelf() && isSend != 0) {
							return;
						}

						String talker = (String) XposedHelpers.getObjectField(mhp.thisObject, "field_talker");
						log("xposed, talker：" + talker);
						if (PreferenceUtils.notWhisper() && !isGroupTalk(talker)) {
							return;
						}

						if (!isGroupTalk(talker) && isSend != 0) {
							return;
						}

						if (isGroupTalk(talker) && PreferenceUtils.notMute()) {
							Object msgInfo = XposedHelpers.callStaticMethod(
									findClass("com.tencent.mm.storage.ai", lpp.classLoader), "E", mhp.thisObject);
							boolean notMute = (boolean) callStaticMethod(
									XposedHelpers.findClass("com.tencent.mm.booter.notification.c", lpp.classLoader),
									"a", talker, msgInfo, 3, false);
							if (!notMute) {
								return;
							}
						}

						String content = (String) getObjectField(mhp.thisObject, "field_content");
						XposedBridge.log("xposed, content：" + content);

						String nativeUrlString = getFromXml(content, "nativeurl");
						Uri localUri = Uri.parse(nativeUrlString);
						int msgType = Integer.parseInt(localUri.getQueryParameter("msgtype"));
						int channelId = Integer.parseInt(localUri.getQueryParameter("channelid"));
						String sendId = localUri.getQueryParameter("sendid");

						Object[] obj = new Object[8];
						obj[0] = Integer.valueOf(msgType);
						obj[1] = Integer.valueOf(channelId);
						obj[2] = sendId;
						obj[3] = nativeUrlString;
						obj[4] = "";
						obj[5] = "";
						obj[6] = talker;
						obj[7] = "v1.0";

						Object ab = newInstance(findClass("com.tencent.mm.plugin.luckymoney.c.ab", lpp.classLoader),
								obj);

						int delayTime = PreferenceUtils.delay() ? PreferenceUtils.delayTime() : 0;

						callMethod(
								callStaticMethod(findClass("com.tencent.mm.model.ah", lpp.classLoader), "tv",
										new Object[0]), "d", new Object[] { ab });
					}
				}
			});
		} catch (Throwable e) {
			log("redpacket hook exception," + e.getMessage());
		}
	}

	private  String getFromXml(String xmlStr, String key) throws XmlPullParserException, IOException {
		String xml = xmlStr.substring(xmlStr.indexOf("<msg>"));
		XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
		factory.setNamespaceAware(true);
		XmlPullParser xpp = factory.newPullParser();
		xpp.setInput(new StringReader(xml));
		int eventType = xpp.getEventType();
		String result = "";
		while (eventType != XmlPullParser.END_DOCUMENT) {
			if ((eventType == XmlPullParser.START_TAG) && (xpp.getName().equals(key))) {
				xpp.nextToken();
				result = xpp.getText();
				break;
			}
			eventType = xpp.next();
		}
		return result;
	}

	private  boolean isGroupTalk(String talker) {
		return talker.endsWith("@chatroom");
	}

}
